package com.course.file.controller;

import cn.hutool.core.util.StrUtil;
import com.course.file.service.UploadService;
import com.course.server.common.Result;
import com.course.server.dto.FileDto;
import com.course.server.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author: Durian
 * @date: 2021/5/3 17:32
 */
@Slf4j
@RestController
public class UploadController {

    @Resource
    private FileService fileService;
    @Resource(name = "${upload.address}")
    private UploadService uploadService;

    public static final String BUSINESS_NAME = "文件上传";

    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile shard, FileDto fileDto) throws IOException {
        String path = uploadService.upload(shard, fileDto);
        fileDto.setPath(path);
        fileService.save(fileDto);
        return Result.success(fileDto);
    }

    @PostMapping("/upload/check")
    public Result check(FileDto fileDto) {
        log.info("检查key=【{}】的文件", fileDto.getKey());
        String path = uploadService.check(fileDto);
        FileDto dbFileDto = fileService.findByKey(fileDto.getKey());
        // 数据库记录不存在，Oss存在文件
        if (dbFileDto == null && StrUtil.isNotBlank(path)) {
            // 设置分片上传完成状态
            fileDto.setShardIndex(fileDto.getShardTotal());
            fileDto.setPath(path);
            fileService.save(fileDto);
            return Result.success(fileDto);
        }
        // 数据库记录存在，但是oss没有文件 todo 暂时不考虑
        // oss和数据库记录都不存在
        return Result.success(dbFileDto);
    }
}
